<?php

namespace app\common\model;

use app\common\exception\Exception;
use think\Db;
use think\Hook;
use think\Model;

/**
 * 仪事模型
 */
class Backlog extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    // 追加属性
    protected $append = [
        'images_text',
        'status_text',
        'finishtime_text',
        'createtime_text',
    ];

    //图片数组
    public function getImagesTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['images']) ? $data['images'] : '');
        if (!$value){
            return [];
        }
        $arr = explode(',',$value);
        foreach ($arr as &$item){
            $item = cdnurl($item,true);
        }
        return $arr;
    }

    public function getStatusList()
    {
        return [0=>'待完成',1=>'已完成'];
    }

    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        return !$value ? '' : $this->getStatusList()[$value];
    }

    public function getFinishtimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['finishtime']) ? $data['finishtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getCreatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    //关联用户
    public function user()
    {
        return $this->hasOne(User::class, 'id', 'user_id')->field('id,nickname,avatar');
    }

    public function worker()
    {
        return $this->hasOne(User::class, 'id', 'work_uid')->field('id,nickname,avatar');
    }

    //列表
    public static function getLists($params)
    {
        $status = 'all';
        $type = 'all';
        $user = User::info();
        extract($params);
        if ($status != 'all') {
            $where['status'] = $status;
        }
        if ($type == 'all') {
            $where['user_id | work_uid'] = $user->id;
        }
        if ($type == 'my') {
            $where['user_id'] = $user->id;
        }
        if ($type == 'work') {
            $where['work_uid'] = $user->id;
        }
        return self::where($where)->order('createtime desc')->paginate(10);
    }

    //编辑
    public static function operEdit($params)
    {
        $user = User::info();
        $id = 0;
        extract($params);
        $work_user = User::where(['id' => $work_uid])->find();
        if (!$work_user) {
            new Exception('办事人不存在');
        }
        //id不存在执行添加
        if (!$id){
            $edit = self::create([
                'work_sn'       => self::getSn($user->id),
                'user_id'       => $user->id,
                'user_nickname' => $user->nickname,
                'work_uid'      => $work_user->id,
                'work_nickname' => $work_user->nickname,
                'title'         => $title,
                'content'       => $content,
                'range'         => $range,
                'status'        => 0,
            ]);
        }else{
            //编辑
            $edit = self::update([
                'user_id'       => $user->id,
                'user_nickname' => $user->nickname,
                'work_uid'      => $work_user->id,
                'work_nickname' => $work_user->nickname,
                'title'         => $title,
                'content'       => $content,
                'range'         => $range,
                'id'            => $id
            ]);
        }

        $row = self::where('id',$edit->id)->find();
        //仪事创建后发微信通知
        $data['backlog'] = $row;
        $data['action'] = 'created';
        Hook::listen('send_work_message',$data);
        return $row;
    }

    //删除
    public static function operDel($id)
    {
        $user = User::info();
        return self::where('id',$id)->where('user_id',$user->id)->delete();
    }

    //完成
    public static function operFinish($params)
    {
        $user = User::info();
        $images = [];
        $remark = '';
        extract($params);
        $row = self::find($id);
        if ($row->status != 0){
            new Exception('该仪事已完成');
        }
        if ($row->work_uid != $user->id){
            new Exception('sorry,您没有权限！');
        }
        $row->status = 1;
        $row->remark = $remark;
        $row->images = join(',',$images);
        $row->finishtime = time();
        $row->save();
        //仪事完成后发微信通知
        $data['backlog'] = $row;
        $data['action'] = 'success';
        Hook::listen('send_work_message',$data);
        return $row;
    }

    // 获取订单号
    public static function getSn($user_id)
    {
        $rand = $user_id < 9999 ? mt_rand(10000, 99999) : mt_rand(100, 9999);
        $order_sn = date('Yhis') . $rand;

        $id = str_pad($user_id, (18 - strlen($order_sn)), '0', STR_PAD_BOTH);

        return $order_sn . $id;
    }
}
